/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ohosannotations.api;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

/**
 * UI线程执行者
 *
 * @since 2021-07-20
 */
public final class UiThreadExecutor {
    private static final EventRunner EVENT_RUNNER = EventRunner.getMainEventRunner();
    private static final EventHandler HANDLER = new EventHandler(EVENT_RUNNER) {
        @Override
        protected void processEvent(InnerEvent event) {
            if (event.object != null && event.object instanceof Runnable) {
                ((Runnable) event.object).run();
            } else {
                super.processEvent(event);
            }
        }
    };

    private UiThreadExecutor() {
    }

    /**
     * 执行任务
     *
     * @param task 可运行
     * @param delay 延迟时长
     */
    public static void runTask(Runnable task, long delay) {
        InnerEvent innerEvent = InnerEvent.get(task);
        HANDLER.sendEvent(innerEvent, delay);
    }

    /**
     * 执行任务
     *
     * @param eventId 标识Id
     * @param task 可运行
     * @param delay 延迟时长
     */
    public static void runTask(int eventId, Runnable task, long delay) {
        InnerEvent innerEvent = InnerEvent.get(eventId, task);
        HANDLER.sendEvent(innerEvent, delay);
    }

    /**
     * 取消所有
     *
     * @param eventId 标识ID
     */
    public static void cancelAll(int eventId) {
        HANDLER.removeEvent(eventId);
    }
}
